import { watchThrottled } from '@vueuse/core'
import { config } from "@/utils/setting"

const changeOperationWidth = (childNum, fontSize) => {
    return childNum && fontSize ? ((fontSize * 2 + 5) * childNum + 20) + "px" : "0"
}

const useSetTableOperationWidth = (defaultNum = 4) => {
    const eleNum = defaultNum + 1
    let delay = 300
    const childrenNum = ref(eleNum)

    onUpdated(() => {
        const doms = document.querySelectorAll(".operation-column .cell")
        if (doms.length <= 1) return
        const elements = document.querySelectorAll("colgroup col")
        for (let ele of elements) {
            ele.style.transition = `all .2s`
        }

        childrenNum.value = Math.max(...[...doms].map(ele => ele.childElementCount))
    })

    const width = ref("0")

    watchThrottled([childrenNum, () => config.value.fontSize], ([num, fontSize]) => {
        width.value = changeOperationWidth(num, fontSize)
    }, { throttle: delay, immediate: true })

    return width
}

export default useSetTableOperationWidth